package com.swp.oa.sys.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.swp.oa.comomn.Option;
import com.swp.oa.sys.dao.ILoginStateDao;
import com.swp.oa.sys.dao.IRoleAuthDao;
import com.swp.oa.sys.dao.IRoleDao;
import com.swp.oa.sys.dao.IUserDao;
import com.swp.oa.sys.dao.IUserRoleDao;
import com.swp.oa.sys.pojo.Auth;
import com.swp.oa.sys.pojo.LoginState;
import com.swp.oa.sys.pojo.Role;
import com.swp.oa.sys.pojo.User;
import com.swp.oa.sys.pojo.UserRole;
import com.swp.oa.sys.service.IUserWebService;
import com.swp.oa.util.UUIDGenerator;

@Service("userWebService")
public class UserWebServiceImpl implements IUserWebService{

	@Autowired
	private IUserDao userDao;
	@Autowired
	private ILoginStateDao loginStateDao;
	@Autowired
	private IRoleDao roleDao;
	@Autowired
	private IUserRoleDao userRoleDao;
	@Autowired
	private IRoleAuthDao roleAuthDao;
	//功能还不完善 应该返回一个token
	@Override
	public String userLogin(String username, String password,String loginIp) {
		if(username.equals("") || password.equals("") || loginIp.equals("")){
			return null;
		}
		if(!this.checkIp(loginIp)){
			System.out.println("限制登录。。。");
			return "-1";
		}
//		password = password;
		User user = userDao.selectByUsername(username);
		if(user == null){
			System.out.println("用户不存在");
			return "0";
		}
		if(!user.getUpassword().equals(password)){
			System.out.println("用户密码错误");
			return "1";
		}
		String token = "";
		LoginState state = new LoginState();
		state.setLoginstateid(UUIDGenerator.getUUID());
		state.setUserid(user.getUserid());
		state.setStatus("1");
		state.setToken(UUIDGenerator.getUUID());
		state.setLogincount(1);
		state.setCreatedate(new Date());
		state .setUpdatedate(state.getCreatedate());
		state.setVersion(1);
		state.setNowloginip(loginIp);
		state.setNowlogindate(state.getCreatedate());
		loginStateDao.insertSelective(state);
		token = state.getToken();
		return token;
	}
//	LoginState s = loginStateDao.selectByUserId(user.getUserid());
//	if(s != null){
//		//之前曾经登录过  会有什么行为
////		if(s.getStatus().equals("1")){
////			System.out.println("只能登录一次。。。");
////			return null; //已经登录
////		}
//		s.setLastloginip(s.getNowloginip());
//		s.setNowloginip(loginIp);
//		s.setLastlogindate(s.getNowlogindate());
//		s.setNowlogindate(new Date());
//		s.setUpdatedate(s.getNowlogindate());
//		s.setLogincount(s.getLogincount() + 1);
//		s.setStatus("1");
//		s.setToken(UUIDGenerator.getUUID());
//		loginStateDao.updateByPrimaryKeySelective(s);
//		token = s.getToken();
//	}else{
//		//第一次登录
//		LoginState state = new LoginState();
//		state.setLoginstateid(UUIDGenerator.getUUID());
//		state.setUserid(user.getUserid());
//		state.setStatus("1");
//		state.setToken(UUIDGenerator.getUUID());
//		state.setLogincount(1);
//		state.setCreatedate(new Date());
//		state .setUpdatedate(state.getCreatedate());
//		state.setNowloginip(loginIp);
//		state.setNowlogindate(state.getCreatedate());
//		loginStateDao.insertSelective(state);
//		token = state.getToken();
//	}	
	@Override
	public boolean userLogout(String username, String token) {
		if(username.equals("")){
			return false;
		}
//		User user = userDao.selectByUsername(username);
//		LoginState state = loginStateDao.selectByToken(token);
//		if(!user.getUserid().equals(state.getUserid())){
//			return false;
//		}
//		state.setStatus("0");
//		state.setUpdatedate(new Date());
//		state.setToken(null);
//		loginStateDao.updateByPrimaryKey(state);
		loginStateDao.deleteByToken(token);
		return true;
	}

	@Override
	public boolean validateOperation(String userId,String operation) {
		if(userId.equals("")){
			return false;
		}
		User user = userDao.selectByPrimaryKey(userId);
		//根据 authjsonsata字段查找
		if(user.getAuthjsondata() != null){
			JSONArray json =new JSONArray();
			for (int i = 0; i < json.size(); i++) {
				if(json.getString(i).equals(operation)){
					return true;
				}
			}
		}else{
			UserRole userRole = userRoleDao.selectByUserId(user.getUserid());
			Role role = roleAuthDao.selectAuthsByRoleId(userRole.getRoleid());
			if(role != null){
				List<Auth> auths = role.getAuths();
				for (Auth auth : auths) {
				if(auth.getCode().equals(operation)){
					return true;
				}
				}
			}
		}
		return false;
	}
	@Override
	public boolean validateOperationIsOptimized(String userId, String operation) {
		if(userId.equals("")){
			return false;
		}
		UserRole userRole = userRoleDao.selectByUserId(userId);
		Role role = roleAuthDao.selectAuthsByRoleId(userRole.getRoleid());
		if(role != null){
			List<Auth> auths = role.getAuths();
			for (Auth auth : auths) {
			if(auth.getCode().equals(operation)){
				return true;
			}
			}
		}
		return false;
	}
	@Override
	public Role getUserRoleByUserName(String username, String token) {
		if(username.equals("")){
			return null;
		}
		User user = userDao.selectByUsername(username);
		User u = userRoleDao.selectRolesByUserId(user.getUserid());
		Role role = u.getRoles().get(0);
		return role;
	}

	@Override
	public List<String> getUserAuths(String username, String token) {
//		System.out.println("username: " + username);
		if(username.equals("")){
			return null;
		}
		User user = userDao.selectByUsername(username);
		if(user != null){
			User u = userRoleDao.selectRolesByUserId(user.getUserid());
			Role role = u.getRoles().get(0);
			Role roleAuths = roleAuthDao.selectAuthsByRoleId(role.getRoleid());
			List<Auth> auths = roleAuths.getAuths();
			List<String> list = new ArrayList<String>();
			for(Auth auth : auths){
//				System.out.println("auth.getCode(): " + auth.getCode());
				list.add(auth.getCode());
			}
			return list;
		}
		return null;
	}

	@Override
	public String getUserIdByToken(String token) {
		LoginState loginState = loginStateDao.selectByToken(token);
		if(loginState != null){
			return loginState.getUserid();
		}
		return null;
	}
	@Override
	public boolean checkPasswordIsPast(String userId) {
		User user = userDao.selectByPrimaryKey(userId);
		 // 创建 Calendar 对象  
	    Calendar oldCalendar = Calendar.getInstance();  
	    // 初始化 Calendar 对象，但并不必要，除非需要重置时间  
	    oldCalendar.setTime(user.getLastupdatepwddate());  
	    Calendar newCalendar = Calendar.getInstance();
	    newCalendar.setTime(new Date());
	    // 今年的第 N 天  
	    int old = oldCalendar.get(Calendar.DAY_OF_YEAR); 
	    int nowDate = newCalendar.get(Calendar.DAY_OF_YEAR); 
		int num = newCalendar.get(Calendar.YEAR) - oldCalendar.get(Calendar.YEAR);
		if(num >= 2){
			return true;
		}
		if(num == 1){
			if( (365 - old + nowDate) > Option.getChangePassWordCycle()){
				return true;
			}
		}else{
			if(365 - old > Option.getChangePassWordCycle()){
				return true;
			}
		}
		return false;
	}

	private boolean checkIp(String ip){
		ip = ip.trim();
		String[] ips = ip.replace(".", "/").split("/");
		List<String> ipList = Option.getIPs();
		for (String optionIP : ipList) {
			optionIP = optionIP.trim();
			String[] netIps = optionIP.replace(".", "/").split("/");
			int flag = 0;
			for (int i = 0; i < netIps.length ; i++) {
				if(netIps[i].equals("*") || netIps[i].equals(ips[i])){
					flag++;
				}else{
					break;
				}
			}
//			System.out.println("chckIp flag: " + flag);
			if(flag >= 3){
				return true;
			}			
		}
		
		return false;
	}

	

}
